package com.echo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        List<String> allowedOrigins = new ArrayList<>();

        // 方便前端访问：生成localhost的8000-8010端口
        for (int port = 8000; port <= 8010; port++) {
            allowedOrigins.add("http://localhost:" + port);
        }

        // 方便前端访问：生成106.53.113.145的8000-8010端口
        String ip = "106.53.113.145";
        for (int port = 8000; port <= 8010; port++) {
            allowedOrigins.add("http://" + ip + ":" + port);
        }

        // 添加其他原有的允许地址
        allowedOrigins.addAll(Arrays.asList(
                "http://192.168.109.1:8000",
                "http://localhost:5177",
                "http://106.53.113.145:5177",
                "http://106.53.113.145:9898",
                "http://106.53.113.145:9527",
                "http://106.53.113.145"
        ));

        registry.addMapping("/**") // 允许所有路径跨域
                .allowedOrigins(allowedOrigins.toArray(new String[0]))
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .allowedHeaders("*")
                .exposedHeaders("Authorization")
                .maxAge(3600);
    }
}